import { useControlsStore } from '@/store/controls';
import { useWebSiteStore } from '@/store/web/site';
import { defineStore, acceptHMRUpdate } from 'pinia'
import { CONTROL_TYPES, COMPONENT_TYPES,CALENDER_TYPE_MAP,EVENT_HOVER_TYPES } from '@/const/'
import { WbComponentDatas } from '@/const/web/'
import { getMainListEventByEvents } from '@/components/events/utils/'

export function dealVoteList() {
  const useWebControls = useWebControlsStore()
  const currentControls = useWebControls.currentControls
  if (!currentControls) {
    return
  }
  const voteItem = currentControls[CONTROL_TYPES.wb_vote] //1001
  if (voteItem) {
    let lists: any | IListItem[]
    const componentData = useWebControls.currentData as IComponent
    const mainControlId = getMainListEventByEvents(componentData.events!).controlId
    if (mainControlId && mainControlId != CONTROL_TYPES.wb_vote) {
      let data = currentControls[mainControlId].data as any
      if (data.elements) {
        lists = data.elements
      }
    } else {
      lists = componentData.lists
    }
    _.forEach(lists, (item: ISortItem, index: number) => {
      item.voteId = index + 1
    })
    if (componentData.cid == COMPONENT_TYPES.wb_calendar) {
      if (!lists) {
        lists = []
      }
      while (lists.length > 0) {
        lists.pop()
      }

      let dateStr = ""
      if (componentData.commonAttr.calendarType == CALENDER_TYPE_MAP.currentMonth) {
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        dateStr = year + "/" + month + "/" + 1
        componentData.commonAttr.minDate = dateStr
      } else {
        dateStr = componentData.commonAttr.minDate
      }
      let arr = dateStr.split("/")
      let month = arr[1]
      let year = arr[0]

      let d = new Date(Number(year), Number(month), 0)
      let days = d.getDate()
      let month_ = ''
      let day_ = ''
      for (let i = 1; i <= days; i++) {
        month_ = Number(month) <= 9 ? "0" + month.toString() : month.toString()
        day_ = i <= 9 ? "0" + i.toString() : i.toString()
        lists.push({ voteId: year.toString() + month_ + day_ })
      }
    }
    let data = voteItem.data as IVoteControl
    let voteElements = data.elements
    let key: number = -1
    let voteObj = {}
    if (_.isArray(lists)) {
      _.forEach(lists, (item: any | IListItem, index: number) => {
        /* eslint-disable */
        if (item.hasOwnProperty('voteId')) {
          key = item['voteId']
        } else {
          item.voteId = _.toString(index + 1)
          key = item.voteId
        }
        /* eslint-disable */
        if (voteElements.hasOwnProperty(key)) {
          voteObj[key] = voteElements[key]
        } else {
          if (key > 0) {
            voteObj[key] = { 'base': 0, 'total': 0, 'num': 0, 'progress': 0 }
          }
        }
      })
    } else {
      let index = 0
      key = index + 1
      /* eslint-disable */
      if (voteElements.hasOwnProperty(key)) {
        voteObj[key] = voteElements[key]
      } else {
        if (key > 0) {
          voteObj[key] = { 'base': 0, 'total': 0, 'num': 0, 'progress': 0 }
        }
      }
    }
    data.elements = voteObj
  }
}


export const useWebControlsStore = defineStore('webControls', {
  state: (): IWebControlsStore => {
    return {
      controls: {},
      currentControls: {},
      currentData: null
    }
  },
  getters: {
    isLottery() {
      const useWebSite = useWebSiteStore()
      const pages = useWebSite.siteData && (useWebSite.siteData as IWebSiteData_).pages
      if(!pages || pages.length < 0){
        return false
      }
      const pageLen = pages.length
      let isLottery = false
      for(let i = 0; i < pageLen; i++){
        const page = pages[i]
        const components = page.components
        let componentData: any | IComponent
        let events: any
        for(let j = 0, len = components.length; j < len; j++){
          componentData = components[j]
          events = componentData.events
          if(events[EVENT_HOVER_TYPES.lottery]){
            isLottery = true
            break
          }
        }
      }
      return isLottery
    }
  },
  actions: {
    setControls(data: IControlsMap | any) {
      this.controls = {}
      // 编辑端与移动端公用 controls
      useControlsStore().controls = this.controls
      for (let id in data) {
        this.controls[id] = data[id]
      }
    },
    setActiveWbData(currentData : IComponent | null | IPage) {
      //页面或是组件数据
      this.currentData = currentData
      if (currentData && currentData.id) {
        /* eslint-disable */
        if (this.controls.hasOwnProperty(currentData.id)) {
          this.currentControls = this.controls[currentData.id]
        } else {
          this.controls[currentData.id] = {}
          this.currentControls = this.controls[currentData.id]
        }
      } else {
        //删除组件
        this.currentControls = null
      }
    },
    setControlById({ compId, newCompId } : {compId:string , newCompId: string}) {
      let controlData = this.controls[compId]
      delete this.controls[compId]
      this.controls[newCompId] = controlData
    },
    addEventControlToControls({ copyId, compId }:{ copyId: string, compId: string }) {
      this.controls[compId] = _.cloneDeep(this.controls[copyId])
    },
    addEventControlToCurrentControls(controlId: string) {
      if (!WbComponentDatas[controlId]) {
        return
      }
      const controlData = _.cloneDeep(WbComponentDatas[controlId])
      this.currentControls![controlId] = controlData
      dealVoteList()
    },
    deleteEventControlToControls({ event, id }) {
      let controlId = event.controlId
      delete this.currentControls![controlId];

      if (_.size(this.currentControls) == 0) {
        delete this.controls[id]
      }
    },
    addWbComponentItem({ controlId, item }) {
      const baseControl = this.currentControls![controlId] as IBaseControl
      const wbList = (baseControl.data as IBaseListControl).elements
      wbList.push(item)
      dealVoteList()
    },
    updateWbComponentItem({ index, item, controlId }) {
      const baseControl = this.currentControls![controlId] as IBaseControl
      let wbList: any
      if (baseControl.data as IBaseListControl) {
        wbList = (baseControl.data as IBaseListControl).elements
      } else {
        wbList = this.currentControls![controlId].data
      }
      if (_.isString(item)) {
        wbList[index] = item
      } else if (controlId == CONTROL_TYPES.wb_push && item.pics) {
        if (wbList[index].pics.length != item.pics.length) {
          wbList[index].pics = []
        }
        _.merge(wbList[index], item)
      } else {
        _.merge(wbList[index], item)
      }
      dealVoteList()
    },
    deleteWbComponentItem({ index, controlId }) {
      const baseControl = this.currentControls![controlId] as IBaseControl
      const wbList = (baseControl.data as IBaseListControl).elements
      wbList.splice(index, 1)
      dealVoteList()
    },
    updateWbComponent({ data, controlId }) {
      _.merge(this.currentControls![controlId].data, data)
    },
    deleteControl(id: string) {
      delete this.controls[id];
    },
    dealVoteListCommit() {
      dealVoteList()
    },
  },
})

if (import.meta.hot) {
  import.meta.hot!.accept(acceptHMRUpdate(useWebControlsStore, import.meta.hot))
}